建立完Core Data的設定後,接下來要將Core Data的功能加入程式碼,今天會使用昨天創建的「DateInfo」Entity示範如何在Xcode中存取Core Data資料。
參考資料:https://www.youtube.com/watch?v=gWurhFqTsPU
import CoreData
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let dateInfo = NSEntityDescription.insertNewObject(forEntityName: "DateInfo", into: context) as! DateInfo
dateInfo.date = "2020-9-28"
dateInfo.eventCount = Int16(3)
dateInfo.uuid = UUID()
do{
try context.save()
print(dateInfo)
}catch let createError{
print("Failed to create :\(createError)")
}
let fetchRequestRead = NSFetchRequest<DateInfo>(entityName: "DateInfo")
fetchRequestRead.fetchLimit = 1
fetchRequestRead.predicate = NSPredicate(format: "date == %@", "2020-9-28")
do{
let dateInfoRead = try context.fetch(fetchRequestRead)
print(dateInfoRead[0])
}catch let fetchError{
print("Failed to fetch compaies: \(fetchError)")
}
let fetchRequestUpdate = NSFetchRequest<DateInfo>(entityName: "DateInfo")
fetchRequestUpdate.fetchLimit = 1
fetchRequestUpdate.predicate = NSPredicate(format: "date == %@", "2020-9-28")
do{
let dateInfoUpdate = try context.fetch(fetchRequestUpdate)
dateInfoUpdate[0].eventCount = Int16(4)
do{
try context.save()
print(dateInfoUpdate[0])
} catch let createError{
print("Failed to update: \(createError)")
}
}catch let fetchError{
print("Failed to fetch compaies: \(fetchError)")
}
let fetchRequestDelete = NSFetchRequest<DateInfo>(entityName: "DateInfo")
fetchRequestDelete.fetchLimit = 1
fetchRequestDelete.predicate = NSPredicate(format: "date == %@", "2020-9-28")
do{
let dateInfoDelete = try context.fetch(fetchRequestDelete)
context.delete(dateInfoDelete[0])
do{
try context.save()
print(dateInfoDelete[0])
} catch let createError{
print("Failed to update: \(createError)")
}
}catch let fetchError{
print("Failed to fetch compaies: \(fetchError)")
}
除了上述介紹的基本資料存取外,Core Data還有很多其他好用的功能,大家可以依據自己的App使用相對應的存取方式,也歡迎在下方留言和我討論。
「顏色」App的資料庫筆記到這邊告一段落,接下來會和大家分享前端各種介面的製作方式!